from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from sqlalchemy import text
from backend.database import SessionLocal
from backend.models import User
from backend.schemas import UserResponse, UserCreate, UpdateProfile, ChangePassword
from . import models, schemas
from datetime import datetime
from . import job_routes, resume_routes, forum_routes, message_routes, resource_routes
from . import application_routes
from . import user_routes

app = FastAPI()

# 注册所有路由

app.include_router(job_routes.router)
app.include_router(resume_routes.router)
app.include_router(forum_routes.router)
app.include_router(message_routes.router)
app.include_router(application_routes.router)
app.include_router(resource_routes.router)
app.include_router(user_routes.router)

# 启用 CORS
app.add_middleware(
    CORSMiddleware,
    # allow_origins=["http://localhost:8080", "http://127.0.0.1:8080"],
    allow_origins=["*"],  # 允许所有域名
    allow_methods=["*"],  # 允许所有方法
    allow_credentials=True,
    allow_headers=["*"],  # 允许所有头
)

@app.get("/")
def read_root():
    return {"message": "nihao!"}



def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


#注册功能
@app.post("/api/register", response_model=schemas.UserResponse)
async def register_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    # 1. 检查用户名和邮箱
    if db.query(models.User).filter(models.User.username == user.username).first():
        raise HTTPException(status_code=400, detail="用户名已存在")
    if db.query(models.User).filter(models.User.email == user.email).first():
        raise HTTPException(status_code=400, detail="邮箱已注册")

    # 2. 自动创建用户 (使用字典解包)
    db_user = models.User(
        **user.dict(exclude={"password"}),  # 排除需要特殊处理的字段
        password=user.password,  # 单独处理密码字段
        created_at=datetime.utcnow(),
        is_active=True
    )

    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


@app.post("/login")
async def login(data: schemas.Login, db: Session = Depends(get_db)):
    # 检查用户名是否存在
    user = db.query(models.User).filter(models.User.username == data.username).first()
    if not user:
        raise HTTPException(status_code=400, detail="用户名不存在")

    # 检查密码是否正确
    if data.password != user.password:
        raise HTTPException(status_code=400, detail="密码错误")

    # 检查用户是否激活
    if not user.is_active:
        raise HTTPException(status_code=403, detail="账号未激活，请联系管理员")

    return {
        "success": True,
        "message": "登录成功",
        "user_id": user.user_id,
        "token": "mock_token-" + str(user.user_id),
        "user_type": user.user_type,
        "is_active": user.is_active
    }

# 用户信息接口

@app.get("/api/user-info")
async def read_user_info(user_id: int, db: Session = Depends(get_db)):

    user = db.query(models.User).filter(models.User.user_id == user_id).first()

    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return {
        "username": user.username,
        "user_type": user.user_type,
        "email": user.email,
        "phone": user.phone
    }

# 登出接口
@app.post("/api/logout")
async def logout():
    # 实际项目中应该将token加入黑名单
    return {"message": "Successfully logged out"}

@app.post("/api/updateprofile")
async def update_profile(update_data: schemas.UpdateProfile, db: Session = Depends(get_db)):
    # 从token中获取用户ID
    user_id = update_data.user_id  # 假设前端传入了user_id
    user = db.query(models.User).filter(models.User.user_id == user_id).first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新用户资料
    user.email = update_data.email
    user.phone = update_data.phone
    
    # 提交更改
    db.commit()
    db.refresh(user)
    return {"message": "资料更新成功"}


@app.post("/api/changepassword")
async def change_password(password_data: schemas.ChangePassword, db: Session = Depends(get_db)):
    # 从token中获取用户ID
    user_id = password_data.user_id  # 假设前端传入了user_id
    user = db.query(models.User).filter(models.User.user_id == user_id).first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 验证当前密码
    if password_data.current_password != user.password:
        raise HTTPException(status_code=400, detail="当前密码不正确")
    
    # 更新密码
    user.password = password_data.new_password
    
    # 提交更改
    db.commit()
    
    return {"message": "密码修改成功"}